//------------------------------------------------------------------------------
// <copyright file="HandleExceptions.cs" company="Damian Antonowicz">
//       copyright © 2010 Damian Antonowicz
// </copyright>
// <author>Damian Antonowicz</author>
// <email>poczta@damianantonowicz.pl</email>
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using DotBeer.Business.Entities.StringKeys;

// This class is modified implementation of HandleExceptions posted at:
// http://www.maciejaniserowicz.com/post/2009/08/24/Zwiezla-obsluga-wyjatkow-z-Enterprise-Library.aspx
//

namespace DotBeer.Business.Components.Exceptions
{
    public static class HandleExceptions
    {
        #region public methods

        public static void UIPolicy(Exception ex)
        {
            Handle(ex, Policies.UIPolicy);
        }

        public static void UIPolicy(Action operation)
        {
            Handle(operation, Policies.UIPolicy);
        }

        public static void BusinessLogicPolicy(Exception ex)
        {
            Handle(ex, Policies.BusinessLogicPolicy);
        }

        public static void BusinessLogicPolicy(Action operation)
        {
            Handle(operation, Policies.BusinessLogicPolicy);
        }

        public static void UpdatePolicy(Exception ex)
        {
            Handle(ex, Policies.UpdatePolicy);
        }

        public static void UpdatePolicy(Exception ex, out Exception exceptionToThrow)
        {
            Handle(ex, Policies.UpdatePolicy, out exceptionToThrow);
        }

        #endregion

        #region private methods

        private static void Handle(Exception ex, string policyName)
        {
            bool rethrow = ExceptionPolicy.HandleException(ex, policyName);

            if (rethrow)
                throw ex;
        }

        private static void Handle(Exception ex, string policyName, out Exception exceptionToThrow)
        {
            ExceptionPolicy.HandleException(ex, policyName, out exceptionToThrow);
        }

        private static void Handle(Action operation, string policyName)
        {
            try
            {
                operation();
            }
            catch (Exception ex)
            {
                bool rethrow = ExceptionPolicy.HandleException(ex, policyName);

                if (rethrow)
                    throw ex;
            }
        }

        private static T Handle<T>(Func<T> operation, string policyName)
        {
            T ret = default(T);

            Handle(() =>
            {
                ret = operation();
            }, policyName);

            return ret;
        }

        #endregion
    }
}
